import { defineComponent, ref, inject, computed } from 'vue'
import type { Ref } from 'vue'
import { getOptions } from '@/utils/dyForm'
import type { addRuleState } from '@/types/form'
import { getWayOptins } from '@/enum/wayEnum'
import dataTypeEnum from '@/enum/dataTypeEnum'
import type { dyFormOptionsState, questionSideListState } from '@/types/baseConfig'
import type { FormInst } from 'naive-ui'
import {
  NDrawer,
  NDrawerContent,
  NForm,
  NFormItem,
  NSelect,
  NSwitch,
  NDynamicTags,
  NInputNumber,
  NInput,
  NButton
} from 'naive-ui'
export default defineComponent({
  emits: ['save'],
  setup(props, { emit, expose }) {
    const wayOptions = computed(() => {
      return getWayOptins(queryForm.value.dataType)
    })
    const questions = inject('questions') as Ref<questionSideListState[]>

    const options = computed(() => {
      return getOptions(questions.value)
    })

    const handleUpdateValue = (e: string) => {
      const opitem = options.value.find((el: dyFormOptionsState) => {
        return el.labelKey === e
      })
      if (opitem) {
        queryForm.value.dataType = opitem.dataType
      } else {
        queryForm.value.dataType = 'string'
      }
    }

    const show = ref(false)
    const formRef = ref<FormInst | null>(null)
    const queryForm = ref<addRuleState>({
      way: 'noeqEmpty',
      isItem: true,
      dataType: 'string',
      labelKey: '',
      value: '',
      errTip: ''
    })
    const rules = {
      labelKey: {
        required: true,
        message: '请输入字段key',
        trigger: ['input']
      },
      errTip: {
        required: true,
        message: '请输入失败提示语句',
        trigger: ['input']
      }
    }
    const wayChange = (e: any) => {
      queryForm.value.way = e
      setDefaultValue()
    }
    const setDefaultValue = () => {
      if (['includes', 'noincludes'].includes(queryForm.value.way)) {
        queryForm.value.value = []
      } else if (queryForm.value.dataType === 'number') {
        queryForm.value.value = 0
      } else if (queryForm.value.dataType === 'boolean') {
        queryForm.value.value = false
      } else {
        queryForm.value.value = ''
      }
    }

    const handSave = () => {
      formRef.value?.validate(errors => {
        if (errors) {
          return
        }
        emit('save', queryForm.value)
        close()
      })
    }

    const close = () => {
      show.value = false
    }

    const open = (e?: addRuleState) => {
      if (e) {
        queryForm.value = e
      } else {
        queryForm.value = {
          way: 'noeqEmpty',
          isItem: true,
          dataType: 'string',
          labelKey: '',
          value: '',
          errTip: ''
        }
      }
      show.value = true
    }

    expose({
      open
    })

    return () => (
      <>
        <NDrawer v-model:show={show.value} width={400}>
          <NDrawerContent title="添加条件">
            <NForm ref={formRef} model={queryForm.value} rules={rules}>
              <NFormItem label="判断条件" path="way">
                <NSelect
                  value={queryForm.value.way}
                  options={wayOptions.value}
                  placeholder="请选择"
                  onUpdateValue={wayChange}
                />
              </NFormItem>
              <NFormItem label="是否本表" path="isItem">
                <NSwitch v-model:value={queryForm.value.isItem} />
              </NFormItem>
              {queryForm.value.isItem ? (
                <>
                  <NFormItem label="字段" path="labelKey">
                    <NSelect
                      v-model:value={queryForm.value.labelKey}
                      options={options.value}
                      filterable
                      label-field="labelName"
                      placeholder="请输入字段"
                      tag
                      value-field="labelKey"
                      onUpdateValue={handleUpdateValue}
                    />
                  </NFormItem>
                </>
              ) : (
                <>
                  <NFormItem label="数据类型" path="dataType">
                    <NSelect
                      v-model:value={queryForm.value.dataType}
                      options={dataTypeEnum}
                      placeholder="请选择"
                      onUpdateValue={setDefaultValue}
                    />
                  </NFormItem>
                  {queryForm.value.way && queryForm.value.way !== 'noeqEmpty' && (
                    <>
                      <NFormItem label="值" path="value">
                        {['includes', 'noincludes'].includes(queryForm.value.way) &&
                        ['number', 'string'].includes(queryForm.value.dataType) ? (
                          <NDynamicTags v-model:value={queryForm.value.value} />
                        ) : queryForm.value.dataType === 'number' ? (
                          <NInputNumber
                            class="w-full"
                            v-model:value={queryForm.value.value}
                            clearable
                            placeholder="请输入值"
                          />
                        ) : queryForm.value.dataType === 'boolean' ? (
                          <NSwitch v-model:value={queryForm.value.value} />
                        ) : (
                          <NInput v-model:value={queryForm.value.value} placeholder="请输入值" />
                        )}
                      </NFormItem>
                    </>
                  )}
                </>
              )}
              <NFormItem label="失败提示语句" path="errTip">
                <NInput v-model:value={queryForm.value.errTip} placeholder="请输入" />
              </NFormItem>
              <NFormItem>
                <div class="flex justify-end w-full">
                  <NButton type="primary" onClick={handSave}>
                    <span>保存</span>
                  </NButton>
                </div>
              </NFormItem>
            </NForm>
          </NDrawerContent>
        </NDrawer>
      </>
    )
  }
})
